require('dotenv').config()
// 导入数据库操作模块
const db = require('../../db')

// MARK 审批管理

// MARK PUT / user / process / instance / { page } / { size }	查询申请列表
exports.getList = (req, res) => {
  const { page, pageSize } = req.params

  // 验证输入数据
  if (!page || !pageSize || page <= 0 || pageSize <= 0) {
    return res.status(400).json({ success: false, code: 10001, message: '页码和每页大小必须为正整数' })
  }

  // 构建查询条件
  const offset = (parseInt(page) - 1) * parseInt(pageSize)

  // 查询 approval 表
  const approvalQuery = `
    SELECT 
      id AS processId,
      name AS processName,
      state AS processState,
      userId,
      applyTime AS procApplyTime,
      endTime AS procEndTime,
      currNodeUserId
    FROM approval
    ORDER BY state <= 1 DESC, state ASC
    LIMIT ? OFFSET ?
  `
  const values = [parseInt(pageSize), offset]

  db.query(approvalQuery, values, (err, approvalResults) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10002, message: '查询审批信息失败', error: err.message })
    }

    const userIds = approvalResults.map(approval => approval.userId)
    const currNodeUserIds = approvalResults.map(approval => approval.currNodeUserId)

    // 查询 total 记录数
    const totalQuery = `
      SELECT COUNT(*) AS total 
      FROM approval
    `
    db.query(totalQuery, [], (err, totalResult) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10002, message: '查询审批总数失败', error: err.message })
      }

      const total = totalResult[0].total

      // 查询 employee 表
      const employeeIds = Array.from(new Set([...userIds, ...currNodeUserIds]))
      const employeeQuery = `
        SELECT 
          id,
          username
        FROM employee
        WHERE id IN (${employeeIds.map(() => '?').join(', ')})
      `
      db.query(employeeQuery, employeeIds, (err, employeeResults) => {
        if (err) {
          return res.status(500).json({ success: false, code: 10002, message: '查询员工信息失败', error: err.message })
        }

        const employeeMap = employeeResults.reduce((acc, employee) => {
          acc[employee.id] = employee.username
          return acc
        }, {})

        // 处理结果
        const rows = approvalResults.map(approval => ({
          processId: approval.processId,
          processName: approval.processName,
          processState: approval.processState,
          userId: approval.userId,
          username: employeeMap[approval.userId] || '',
          procApplyTime: approval.procApplyTime,
          procCurrNodeUserId: approval.currNodeUserId,
          procCurrNodeUserName: employeeMap[approval.currNodeUserId] || '',
          procEndTime: approval.procEndTime
        }))

        // 计算统计信息
        const currApproveCount = approvalResults.filter(approval => approval.processState === '1').length
        const approveCount = approvalResults.filter(approval => approval.processState === '2').length
        const rejectionCount = approvalResults.filter(approval => approval.processState === '3').length

        // 返回数据
        res.json({
          success: true,
          code: 10000,
          data: {
            total,
            rows,
            currApproveCount,
            approveCount,
            rejectionCount
          },
          message: '执行成功'
        })
      })
    })
  })
}
exports.pass = (req, res) => {
  const { id } = req.params;
  const { statu, applyTime, username, state } = req.query;

  // 验证输入数据
  if (!id) {
    return res.status(400).json({ success: false, code: 10022, message: '审批ID不能为空' });
  }

  if (!state) {
    return res.status(400).json({ success: false, code: 10023, message: '状态不能为空' });
  }

  // 获取当前时间
  const currentTime = new Date().toISOString();

  // 更新 approval 表中的记录
  const updateQuery = `
    UPDATE approval
    SET state = ?, EndTime = ?
    WHERE id = ?
  `;
  const values = [state, currentTime, id];

  db.query(updateQuery, values, (err, result) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10024, message: '更新审批信息失败', error: err.message });
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, code: 10025, message: '审批记录不存在' });
    }

    // 如果 state 的值为 3，仅更新 approval 表，不处理 attendances 表
    if (state === '3') {
      return res.json({
        success: true,
        code: 10000,
        data: null,
        message: '更新审批信息成功'
      });
    }

    // 根据 username 查询 employee 表，获取 userId
    const employeeQuery = `
      SELECT id
      FROM employee
      WHERE username = ?
    `;
    db.query(employeeQuery, [username], (err, employeeResults) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10026, message: '查询员工信息失败', error: err.message });
      }

      if (employeeResults.length === 0) {
        return res.status(404).json({ success: false, code: 10027, message: '员工不存在' });
      }

      const userId = employeeResults[0].id;

      // 从 applyTime 中提取日期（日）
      // 将 applyTime 转换为标准的日期时间格式
      const formattedApplyTime = applyTime.replace('/', ' ') + ':00'; // 转换为 '2025-04-20 16:19:00'
      const applyDate = new Date(formattedApplyTime);
      const day = applyDate.getDate() - 1; // 从 0 开始

      // 根据 userId 查询 attendances 表，获取 adtStatu 字段
      const attendanceQuery = `
        SELECT adtStatu
        FROM attendances
        WHERE userId = ? AND year = ? AND month = ?
      `;
      const attendanceValues = [userId, applyDate.getFullYear(), applyDate.getMonth() + 1];

      db.query(attendanceQuery, attendanceValues, (err, attendanceResults) => {
        if (err) {
          return res.status(500).json({ success: false, code: 10028, message: '查询考勤信息失败', error: err.message });
        }

        if (attendanceResults.length === 0) {
          return res.status(404).json({ success: false, code: 10029, message: '考勤记录不存在' });
        }

        // 获取 adtStatu 字段并转换为数组
        const adtStatuString = attendanceResults[0].adtStatu;
        const adtStatuArray = adtStatuString.split('、').map(Number);

        // 修改第 day 个元素的值
        adtStatuArray[day] = parseInt(statu);

        // 转换回字符串
        const updatedAdtStatuString = adtStatuArray.join('、');

        // 更新 attendances 表
        const updateAttendanceQuery = `
          UPDATE attendances
          SET adtStatu = ?
          WHERE userId = ? AND year = ? AND month = ?
        `;
        const updateAttendanceValues = [updatedAdtStatuString, userId, applyDate.getFullYear(), applyDate.getMonth() + 1];

        db.query(updateAttendanceQuery, updateAttendanceValues, (err) => {
          if (err) {
            return res.status(500).json({ success: false, code: 10030, message: '更新考勤信息失败', error: err.message });
          }

          res.json({
            success: true,
            code: 10000,
            data: null,
            message: '更新审批信息成功'
          });
        });
      });
    });
  });
};
// MARK 发起申请
exports.applicate = (req, res) => {
  const { name } = req.body;
  const userId = req.user.id;

  // 验证输入数据
  if (!name) {
    return res.status(400).json({ success: false, code: 10001, message: '申请名称不能为空' });
  }

  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  const applyTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  // 插入数据到 approval 表
  const insertQuery = `
    INSERT INTO approval (name, userId, applyTime)
    VALUES (?, ?, ?)
  `;
  const values = [name, userId, applyTime];

  db.query(insertQuery, values, (err, result) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10002, message: '插入申请记录失败', error: err.message });
    }

    res.json({
      success: true,
      code: 10000,
      data: { id: result.insertId },
      message: '申请提交成功'
    });
  });
}

// // MARK GET / user / process / instance / tasks / { id }	查询审批明细
// // MARK GET / user / process / definition	查询流程定义
// // MARK GET / user / process / suspend / { processKey }	设置流程挂起 / 激活状态


// {
//   "success": true,
//   "code": 10000,
//   "data": {
//       "total": 7,
//       "rows": [
//           {
//               "processId": 1,
//               "processKey": "process_leave",
//               "processName": "请假",
//               "processDefinitionId": 1,
//               "processState": 2,
//               "userId": 2,
//               "username": "黑马孙财",
//               "procApplyTime": "2023-06-23 10:56:27",
//               "procCurrNodeUserId": 1,
//               "procCurrNodeUserName": "管理员",
//               "procEndTime": null,
//               "procData": "{\"duration\":\"1\",\"reason\":\"个人原因\",\"holidayType\":\"1\",\"processName\":\"请假\",\"processKey\":\"process_leave\",\"startTime\":\"2019-09-16 00:00:00\",\"applyUnit\":\"按天\",\"endTime\":\"2019-09-17 00:00:00\",\"userId\":\"1066370498633486336\"}",
//               "departmentId": 8,
//               "departmentName": "市场部",
//               "timeOfEntry": "2018-11-04"
//           },
//           {
//               "processId": 2,
//               "processKey": "process_leave",
//               "processName": "请假",
//               "processDefinitionId": 1,
//               "processState": 2,
//               "userId": 2,
//               "username": "黑马孙财",
//               "procApplyTime": "2023-06-23 11:46:27",
//               "procCurrNodeUserId": 2,
//               "procCurrNodeUserName": "管理员 黑马文吉星",
//               "procEndTime": null,
//               "procData": "{\"duration\":\"5\",\"reason\":\"没有原因\",\"holidayType\":\"1\",\"processName\":\"请假\",\"processKey\":\"process_leave\",\"startTime\":\"2019-09-15 00:00:00\",\"applyUnit\":\"按天\",\"endTime\":\"2019-09-19 00:00:00\",\"userId\":\"1066370498633486336\"}",
//               "departmentId": 8,
//               "departmentName": "市场部",
//               "timeOfEntry": "2018-11-04"
//           }
//       ],
//       "currApproveCount": 3,
//       "approveCount": 0,
//       "rejectionCount": 0
//   },
//   "message": "执行成功"
// }